package eu.inmite.harmony.lib.validations.form.adapters;

import eu.inmite.harmony.lib.validations.form.FieldAdapterFactory;
import eu.inmite.harmony.lib.validations.form.annotations.Joined;
import eu.inmite.harmony.lib.validations.form.iface.IFieldAdapter;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentParent;

import java.lang.annotation.Annotation;

/**
 * Adapter that can be used together with {@link Joined} annotation. It gets values from multiple views.
 * @author Tomas Vondracek
 */
public class JoinedAdapter implements IFieldAdapter<Component, String[]> {
    @Override
    public String[] getFieldValue(Annotation annotation, Component fieldView) {
        final int[] viewIds = ((Joined) annotation).value();
        final Component[] views = findViewsInView(viewIds, fieldView);

        final String[] fieldValues = new String[views.length];
        for (int index = 0; index < views.length; index++) {
            Component view = views[index];
            fieldValues[index] = valueFromView(view);
        }
        return fieldValues;
    }

    private String valueFromView(Component view) {
        IFieldAdapter adapter = FieldAdapterFactory.getAdapterForField(view, null);
        if (adapter != null) {
            return String.valueOf(adapter.getFieldValue(null, view));
        }
        return null;
    }

    private static Component[] findViewsInView(int[] viewIds, Component target) {
        final ComponentParent container = target.getComponentParent();
        final Component[] views = new Component[viewIds.length];
        for (int index = 0; index < viewIds.length; index++) {
            int id = viewIds[index];
            views[index] = ((Component) container).findComponentById(id);
        }
        return views;
    }
}
